<?php

class WMQ
{
    protected static $instance = null;
    protected        $request;
    protected        $wmqConfig;
    protected        $message;
    protected        $routingKey;

    public function __construct($config = [])
    {
        $this->message    = $config['message'] ?? null;
        $this->routingKey = $config['routing_key'] ?? null;
        $this->wmqConfig  = config_item('pgc')['wmq'];
    }

    public function get($query = [])
    {
        return $this->send('GET', $query);
    }

    public function post($body = [], $query = [])
    {
        return $this->send('POST', $query, $body);
    }

    public function send($method, $query = [], $body = [])
    {
        if (!isset($this->message)) {
            throw new UnexpectedValueException('message does not exists');
        }
        if (!isset($this->routingKey)) {
            throw new UnexpectedValueException('routing key does not exists');
        }
        if (!isset($this->wmqConfig[$this->message])) {
            throw new UnexpectedValueException('WMQ message does not exists');
        }
        $this->request = new Request($this->wmqConfig[$this->message]['url']);
        $this->request->setHeader('Token', $this->wmqConfig[$this->message]['token']);
        $this->request->setHeader('RouteKey', $this->wmqConfig[$this->message]['routing_keys'][$this->routingKey]);
        if ($method === 'GET') {
            $uri = '/' . $this->message;
            return $this->request->get($uri, $query);
        } else {
            if ($method === 'POST') {
                $query = !empty($query) ? '?' . http_build_query($query) : '';
                $uri   = '/' . $this->message . $query;
                return $this->request->post($uri, $body);
            }
        }
    }

    public function setMessage($msg)
    {
        $this->message = $msg;
    }

    public function getMessage()
    {
        return $this->message;
    }

    public function setRoutingKey($routingKey)
    {
        $this->routingKey = $routingKey;
    }

    public function getRoutingKey()
    {
        return $this->routingKey;
    }

    public function getRequest()
    {
        return $this->request;
    }
}
